package com.zl.filter;

import com.zl.domain.Privilege;
import com.zl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * Created by zhLEi on 2016/4/24.
 */
public class PrivilegeInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = request.getRequestURI(); // /.*\.(?:(?!(css|js|png)))/
        if (uri.equals("/") || uri.equals("/toIndex") || !uri.matches(".*?\\/(?:.*?\\.(?!css$|js$|png$|html$)|[^\\.]*$)")) {
            return true;
        }
        Map<String, Object> userMap = (Map<String, Object>) request.getSession().getAttribute("user");
        if (userMap != null) {
            boolean valid = false;
            List<Privilege> privileges = (List<Privilege>) userMap.get("privileges");
            for (Privilege privilege : privileges) {
                if (privilege.getUrl().equals(uri)) {
                    valid = true;
                    break;
                }
            }
            if (valid) return true;
            else {
                response.sendRedirect(request.getContextPath() + "/noPrivilege.jsp");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView
            modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse
            httpServletResponse, Object o, Exception e) throws Exception {

    }
}
